package org.example;

import javax.net.ssl.*;
import java.io.*;

import java.security.KeyStore;


public class ClientMain {

    public static void main(String[] args) throws Exception {
        // 载入 truststore
        char[] truststorePassword = "password".toCharArray();
        KeyStore truststore = KeyStore.getInstance("JKS");
        InputStream resourceAsStream = ClientMain.class.getClassLoader().getResourceAsStream("keystore.jks");
        truststore.load(resourceAsStream, truststorePassword);

        // 创建和初始化 SSLContext
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(truststore);
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        // 创建 SSLSocket
        SSLSocketFactory factory = context.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket("127.0.0.1", 12345);

        try(BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));){
            writer.write("Hello from client\r\n\r\n");
            writer.flush();

            // 读取响应请求
            StringBuilder response = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null && !line.isEmpty()) {
                response.append(line).append("\r\n");
            }
            System.out.println("Received from server: " + response);

        }finally {
            // 关闭 socket
            socket.close();
        }

    }

}